package cn.catsdad.util;

import cn.catsdad.constant.ICommonWarningType;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间处理工具
 *
 * @author xuyl
 * @version 1.0 2024/6/23
 */
@SuppressWarnings(ICommonWarningType.UNUSED)
public class DateUtil {

    public static final String YEAR = "yyyy";
    public static final String MONTH = "yyyy-MM";
    public static final String DAY = "yyyy-MM-dd";
    public static final String HOUR = "yyyy-MM-dd hh";
    public static final String MINUTE = "yyyy-MM-dd hh";
    public static final String SECOND = "yyyy-MM-dd HH:mm:ss";
    public static final String MILLISECOND = "yyyy-MM-dd HH:mm:ss.SSS";

    private static final String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    public static String formatTime(Date time, String formatterStr) {
        if (time != null && StringUtil.isNotEmpty(formatterStr)) {
            SimpleDateFormat format = new SimpleDateFormat(formatterStr);
            return format.format(time);
        }
        return "";
    }

    public static Date parse(String timeStr, String formatterStr) {
        if (StringUtil.isNotEmpty(timeStr) && StringUtil.isNotEmpty(formatterStr)) {
            SimpleDateFormat format = new SimpleDateFormat(formatterStr);
            try {
                return format.parse(timeStr);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    public static Date genericParse(String dateStr) {
        try {
            return DateUtils.parseDate(dateStr, parsePatterns);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
